package com.spider.admin.scaffold.service.impl;

import com.spider.admin.scaffold.service.LoginService;
import com.spider.admin.scaffold.service.UserService;
import com.spider.admin.scaffold.entity.dto.LoginDTO;
import com.spider.admin.scaffold.entity.model.User;
import com.spider.admin.scaffold.exception.BusinessException;
import com.spider.admin.scaffold.exception.ExceptionDef;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

/**
 * @author xiong.bo
 * @version 1.0
 * @date 2020/10/31 19:11
 */
@Service("loginService")
public class LoginServiceImpl implements LoginService {

    @Autowired
    private UserService userService;
    @Autowired
    private BCryptPasswordEncoder bcryptPasswordEncoder;


    /**
     * 使用BCryptPasswordEncoder加密是不可逆的,
     * 因此通过用户名查找用户,再对比密码是否一致,
     * 这样就要求用户名是唯一的
     *
     * @return
     */
    @Override
    public User login(LoginDTO loginDTO) {
        String username = loginDTO.getUsername();
        String password = loginDTO.getPassword();
        if (!StringUtils.hasText(username) || !StringUtils.hasText(password)) {
            throw new BusinessException(ExceptionDef.ERROR_COMMON_PARAM_NULL);
        }
        User user = userService.findByUsername(username);
        if (user == null) {
            throw new BusinessException(ExceptionDef.ERROR_USER_LOGIN_FAILED);
        }
        if (!bcryptPasswordEncoder.matches(password, user.getPassword())) {
            throw new BusinessException(ExceptionDef.ERROR_USER_LOGIN_FAILED);
        }
        return user;
    }

}
